package com.shinewind.sso.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.pojo.result.Result;
import com.shinewind.sso.entity.MyUser;
import com.shinewind.sso.util.JwtTemplate;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTemplate jwtTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
        String authToken = req.getHeader("Authorization");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //携带了token
        if(StringUtils.isNotEmpty(authToken)){
            //判断token是否过期
            Boolean flag = jwtTemplate.isJwtExpired(authToken);
            Claims claims = jwtTemplate.parseJwt(authToken);
            if(flag == false && claims.containsKey("uid")){
                MyUser user = (MyUser) auth.getPrincipal();
                if(claims.get("uid").toString().equals(user.getUId())){
                    Map<String,Object> userInfo = new HashMap<>();
                    userInfo.put("uid",user.getUId());
                    out.write(new ObjectMapper().writeValueAsString(Result.success(userInfo,true, messageConstant.TOKEN_PASS)));
                    out.flush();
                    out.close();
                }
            }
            else{
                MyUser user = (MyUser) auth.getPrincipal();
                System.out.println("user1:"+user);
                String token = jwtTemplate.createJwt(user.getUId(), user.getUsername(), user.getAuthorities());
                Map<String,Object> userInfo = new HashMap<>();
                userInfo.put("token",token);
                userInfo.put("uid",user.getUId());
                out.write(new ObjectMapper().writeValueAsString(Result.success(userInfo,true, messageConstant.TOKEN_SUCCESS)));
                out.flush();
                out.close();
            }
        }
        else{
            MyUser user = (MyUser) auth.getPrincipal();
            System.out.println("user2:"+user);
            String token = jwtTemplate.createJwt(user.getUId(), user.getUsername(), user.getAuthorities());
            if(redisTemplate.hasKey(user.getUId())){
                //同一账号重复登录了
                Map<String,Object> userInfo = new HashMap<>();
                userInfo.put("token",token);
                userInfo.put("uid",user.getUId());
                out.write(new ObjectMapper().writeValueAsString(Result.fail(false, messageConstant.ACCOUNT_CONCURRENCY)));
                out.flush();
                out.close();
            }
            else{
                redisTemplate.opsForValue().set(user.getUId(),token);
                Map<String,Object> userInfo = new HashMap<>();
                userInfo.put("token",token);
                userInfo.put("uid",user.getUId());
                out.write(new ObjectMapper().writeValueAsString(Result.success(userInfo,true, messageConstant.TOKEN_SUCCESS)));
                out.flush();
                out.close();
            }
        }
    }
}
